package com.hs.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hs.config.ParamConfig;
import com.hs.entity.User;
import com.hs.service.IUserService;
import com.hs.utils.StringUitls;
import io.swagger.v3.core.util.Json;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

/**
 * @Author lxz
 * @Name
 * @Date 2024/12/11 9:53
 */
@RestController
@RequestMapping("/user")
public class UserController extends BaseController {

    @Autowired
    private IUserService userService;

    @PostMapping("search")
    public JSONObject searchhUser(@RequestBody ParamConfig paramConfig) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.isNotBlank(paramConfig.getName()), User::getName, paramConfig.getName());
        Page<User> userPage = new Page<>(paramConfig.getPage(), paramConfig.getSize());
        Page<User> page = userService.page(userPage, wrapper);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("total",page.getTotal());
        jsonObject.put("data",page.getRecords());
        return renderSuccess(jsonObject);
    }

    @PostMapping("save")
    public JSONObject save(@RequestBody User user) {
        if(StringUtils.isBlank(user.getGuid())){
            user.setGuid(StringUitls.getGuid());
        }
        boolean save = userService.saveOrUpdate(user);
        if (save) {
            return renderSuccess(SUCCESS);
        }
        return renderError(PARAM_ERROR);
    }

    @GetMapping("delete")
    public JSONObject delete(String ids) {
        if (StringUtils.isNotBlank(ids)) {
            String[] split = ids.split(",");
            if (split.length > 0) {
                boolean flag = userService.removeBatchByIds(Arrays.asList(split));
                return renderSuccess(flag ? SUCCESS : DELETE_ERROR);
            }
        }
        return renderError(PARAM_ERROR);
    }
}
